﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Orange.Lib.Effective
{
    namespace DelegateUse
    {
        /// <summary>
        /// Use Delegate to call back.
        /// </summary>
        class Demo1
        {
            #region Muticast
            public void Muticast()
            {
                Func<bool> pred = () =>
                {
                    Console.WriteLine("Part1.");
                    return false;
                };
                pred += () =>
                {
                    Console.WriteLine("Part2.");
                    return true;
                };

                var result = pred();
                Console.WriteLine("result is " + (result ? "true" : "false"));

                result = IsTrue(pred);
                Console.WriteLine("result is " + (result ? "true" : "false"));
            }

            public bool IsTrue(Func<bool> pred)
            {
                foreach (Func<bool> item in pred.GetInvocationList())
                {
                    if (item() == false)
                        return false;
                }
                return true;
            }
            #endregion

            #region Event Pattern
            public class LoggerEventArgs : EventArgs
            {
                public string Message { get; set; }
                public int Priority { get; set; }

                public LoggerEventArgs(int p,string m)
                {
                    Priority = p;
                    Message = m;
                }
            }

            public class Logger
            {
                static Logger()
                {
                    instance = new Logger();
                }

                private static Logger instance;
                public static Logger Singleton
                {
                    get { return instance; }
                }
                private Logger() { }

                public event EventHandler<LoggerEventArgs> log;

                public void AddMsg(int priority, string msg)
                {
                    EventHandler<LoggerEventArgs> l = log;
                    if (l != null)
                        l(this, new LoggerEventArgs(priority, msg));
                }
            }

            #endregion
        }
    }
}
